<template>
  <div class="login-section">
    <el-form
      label-position="top"
      label-width="100px"
      :rules="rules"
      :status-icon="true"
      :model="loginForm"
      ref="loginForm"
    >
      <el-form-item label="用户名" prop="name">
        <el-input
          type="text"
          v-model="loginForm.name"
          autocomplete="off"
          placeholder="请输入用户名"
        ></el-input>
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input
          type="password"
          v-model="loginForm.password"
          autocomplete="off"
          placeholder="请输入密码"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submit('loginForm')">登录</el-button>
        <el-button @click="reset('loginForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { login } from "@/service";
export default {
  data() {
    return {
      loginForm: {
        name: "",
        password: "",
      },
      /* 表单验证规则 */
      rules: {
        name: { required: true, message: "请输入用户名", trigger: "blur" },
        password: {
          required: true,
          message: "请输入密码",
          trigger: ["blur"],
        },
      },
    };
  },

  methods: {
    submit(formName) {
      // console.log(formName);
      // validate 对整个表单进行校验
      this.$refs[formName].validate((valid, notPass) => {
        if (valid) {
          // 校验通过,向后端提交数据
          login(this.loginForm).then((res) => {
            if (res.code === 0) {
              // 登陆成功,跳转至首页
              localStorage.setItem("token", res.data.token);
              this.$router.push({
                name: "home",
              });
            } else if (res.code === 1) {
              this.$message.error(res.mes); // 消息提示
            }
          });
        } else {
          console.log("校验未通过项", notPass);
          return false;
        }
      });
    },
    reset(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style>
.login-section {
  padding: 10px 20px;
  width: 500px;
  background-color: #fff;
  margin: 0 auto;
  box-shadow: 0 0 25px #cac6c6;
  border-radius: 10px;
}
</style>